const EC = require('../comm/err-code');
const helper = require('../comm/api-helper');
const FUN = require('../comm/func');
const rCache = require('../model/redis_cache');
const tbPolicy = require('../model/tb_policy');
const dbPcyData = require('../model/model_data');
const express = require('express');
const api = express();

// 获取指定id的策略数据
// page,limit要兼容web前台和php后台box两种情况
// web前台，page和limit为独立字段
// php后台，没有page，limit里逗号分隔page和limit
api.post('/get-by-policy', async(req, resp) => {
  let p = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(p.token);
  if (!uInfo.uid) { // 获取共享策略时uid为0，则按密钥算法校验token合规
    uInfo.uid = helper.ShareTokenToUid(p.token);
    if (uInfo.uid <= 0) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});
  }

  if (!isVaild(p.ids)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':ids'});
  if (!isVaild(p.table)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':table'});
  if (!isVaild(p.fields)) p.fields = '*';
  if (!isVaild(p.cond)) p.cond = [];
  if (!isVaild(p.limit)) p.limit = '';
  if (isVaild(p.page)) p.limit = `${p.page},${p.limit}`; // 兼容web分开传递的情况
  if (!isVaild(p.order)) p.order = '';

  // 获取策略总数
  let total = await dbPcyData.totalOfPolicyIds(uInfo.uid, p.table, p.ids.split(','), p.cond);
  if (total <= 0) {
    res.code = EC.SUCESS;
    res.msg = EC.SUCESS_MSG;
    res.total = 0;
    res.data = [];
    return resp.json(res);
  }

  // 获取策略数据
  let itemInfo = await dbPcyData.findByPolicyIds(uInfo.uid, p.table, p.ids.split(','), p.fields, p.cond, p.limit, p.order);
  if(itemInfo == null) {
    return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});
  }

  // 查询类型信息
  if (p.fields.includes('ch_name')) {
    for (let i in itemInfo)
      itemInfo[i].ch_type = await rCache.get(rCache.N_Ptype, `all-types:${itemInfo[i].type}`, 'ch_name');
  }

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  res.total = total;
  res.data = itemInfo;
  resp.json(res);
})

// 获取指定产品下的所有策略详情，并带回其相关的策略选项信息
api.post('/get-by-product', async(req, resp) => {
  let p = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(p.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if (!isVaild(p.id)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':id'});
  if (!isVaild(p.table)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':table'});
  if (!isVaild(p.page)) p.page = 1;
  if (!isVaild(p.limit)) p.limit = 9999;

  // 获取产品下数据总数
  let total = await dbPcyData.totalByProduct(uInfo.uid, p.table, p.id);
  if (total <= 0) {
    res.code = EC.SUCESS;
    res.msg = EC.SUCESS_MSG;
    res.total = 0;
    res.data = [];
    return resp.json(res);
  }

  // 获取产品下所有策略id
  let itemInfo = await dbPcyData.findByProduct(uInfo.uid, p.table, p.id, `${p.page},${p.limit}`);
  if(itemInfo == null) {
    return resp.json({code:EC.FETCH_DATA_ERROR, msg:EC.FETCH_DATA_ERROR_MSG});
  }

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  res.total = total;
  res.data = itemInfo;
  resp.json(res);
})

// 删除指定策略数据，如果没带id，就删除此策略所有数据
api.post('/delete-dy-policy', async(req, resp) => {
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!isVaild(param.table) || !isNum(param.policy_id)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 检查此policy是否属于uid
  let policyUid = await dbPcyData.queryPcyUid(param.policy_id);
  if (policyUid == -1) return resp.json({code:EC.SUCESS, msg:EC.SUCESS_MSG});
  else if (policyUid != uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  if (parseInt(param.id)) { // 删单条
    dbPcyData.deleteDataRcd(uInfo.uid, param.table, param.policy_id, param.id);
  } else { // 删所有
    dbPcyData.deleteDataRcd(uInfo.uid, param.table, param.policy_id);
  }

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  resp.json(res);
})

module.exports = api;